<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="utf-8">
    <title>在线进制转换</title>
	<style type="text/css">
		.num_text{
			width:100%;
		}
		.error{
			border:3px solid #f00;
		}
	</style>
 </head>
 <body>
 	<div class="num_list">
	</div>
	<script type="text/javascript" src="http://tool.oschina.net/js/jquery/jquery-1.7.2.js"></script>
	<script>
		var hex_array = new Array(2,4,8,10,16,32);
		$(function(){
			init(hex_array);
			$(".num_text").on('input',numChange);
		});
		function numChange(){
			$(".num_text").removeClass("error");
			var num_radix = $(this).attr("radix");
			//console.log(num_radix);
			var num_value = $(this).val();
			if(!num_value || typeof(num_value)=="undefined" || num_value==''){
				if(num_value==''){
					$(".num_text").val('');
				}else{
					$("#radix_"+num_radix).addClass("error");
				}
				return;
			}
			//console.log(num_value);
			for (var i = 0; i < hex_array.length; i++) {
				var radix = hex_array[i];
				var result = hexconver(num_value,num_radix,radix);
				//console.log(result);
				if(radix == num_radix){
					if(result != num_value){
						$("#radix_"+num_radix).addClass("error");
						return;
					}
				}
				if(result == "o"){
					$("#radix_"+num_radix).addClass("error");
					return;
				}
				if(result == "x"){
					$("#radix_"+radix).addClass("error");
					return;
				}
				$("#radix_"+radix).val(result);
			}
		}
		function hexconver(value,radix,toRadix){
			var num = parseInt(value,radix);
			//console.log(num);
			if(isNaN(num)){
				return 'o';
			}
			var result = num.toString(toRadix);
			return isNaN(num)?'x':result;
		}
		function init(hex_array){
			for (var i = 0; i < hex_array.length; i++) {
				var radix = hex_array[i];
				//console.log(radix);
				var item_str = '<div class="num_item">';
				item_str += '<span>'+radix+'进制:</span>';
				item_str += '<input type="text" class="num_text" id="radix_'+radix+'" radix="'+radix+'"/>';
				item_str += '</div><br/>';
				$(".num_list").append(item_str);
			}
		}
	</script>
 </body>
</html>
